package com.ruoyi.common.utils.file;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 文件大小工具类
 *
 * @author tqfeiyang
 * @since 2024/12/4 15:27
 */
public class FileSizeUtils
{
    /**
     * 格式化字节数据
     *
     * @param size 大小，单位字节
     */
    public static String formatSize(Long size) {
        if (size == null || size <= 0) {
            return "";
        }
        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int unitIndex = (int) (Math.log10(size) / 3);
        double unitValue = 1 << (unitIndex * 10);
        return BigDecimal.valueOf(size / unitValue).setScale(0, RoundingMode.HALF_UP) + " " + units[unitIndex];
    }
}
